package org.ysu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.ysu.entity.Family;
import org.ysu.mapper.FamilyMapper;
import org.ysu.service.FamilyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import javax.annotation.Resource;

/**
 * <p>
 * 贫困户表 服务实现类
 * </p>
 *
 * @author LiuJunDa
 * @since 2024-08-16
 */
@Service
public class FamilyServiceImpl extends ServiceImpl<FamilyMapper, Family> implements FamilyService {

    @Resource
    FamilyMapper familyMapper;


    @Override
    public IPage<Family> list(Integer pageNo, Integer pageSize, Long rId, Long fId) {
        // 创建分页对象
        Page<Family> page = new Page<>(pageNo, pageSize);

        // 构建查询条件包装器
        QueryWrapper<Family> wrapper = new QueryWrapper<>();

        // 如果fId不为空，添加以fId开头的筛选条件
        if (fId != null) {
            wrapper.like("f.f_id", fId.toString()); // 按fId记录进行模糊查询
        }

        // 根据rId添加筛选条件
        wrapper.likeRight("f.r_id", rId.toString()); // 使用别名前缀进行筛选

        // 使用分页和查询条件调用自定义的SQL方法
        List<Family> families = familyMapper.selectFamilyWithHeadAndRegion(page, wrapper);
        page.setRecords(families);

        return page;
    }

    @Override
    public Boolean add(Long fId, String pName, String pNumber, Long rId, Long vcId, String province, String city, String county, String township, String village) {
        return this.save(new Family(fId,pName,pNumber,rId,vcId,province,city,county,township,village));
    }

    @Override
    public Boolean check(String value, Long id, String field) {
        QueryWrapper<Family> wrapper = new QueryWrapper<>();
        wrapper.eq(field,value);
        if(id != null){
            wrapper.ne("f_id",id);
        }
        return this.count(wrapper) == 0;
    }

    @Override
    public Boolean update(Long fid, String pname, String pnumber, Long rid, String province, String city, String county, String township, String village) {
        Family family = new Family(
                fid,
                pname,
                pnumber,
                rid,
                province,
                city,
                county,
                township,
                village
        );
        return this.updateById(family);
    }

    @Override
    public Integer count(long rId){
        return familyMapper.countFamiliesByRegionId(rId);
    }

    @Override
    public Family getByIdWithHead(Long id) {
        return familyMapper.getByIdWithHead(id);
    }
}
